package cn.zhouyafeng.itchat4j.tlUtil;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;

public class TulingClient {

	private Logger logger = LoggerFactory.getLogger(TulingClient.class);

	private MyHttpClient myHttpClient = MyHttpClient.getInstance();

	private static String url = "http://www.tuling123.com/openapi/api";
	// private static String apiKey = "e159df614ea14d60b4e5c9c0e688dae4";

	public String textMsgHandle(String apiKey, String text, String userId) {
		String result = "";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("key", apiKey);
		paramMap.put("info", text);
		paramMap.put("userid", userId);
		String paramStr = JSON.toJSONString(paramMap);
		try {
			HttpEntity entity = myHttpClient.doPost(url, paramStr);
			result = EntityUtils.toString(entity, "UTF-8");
			JSONObject obj = JSON.parseObject(result);
			// 100000 文本类
			// 200000 链接类
			// 302000 新闻类
			// 308000 菜谱类
			// 313000 儿歌类
			// 314000 诗词类
			if (obj.getString("code").equals("100000")) {
				result = obj.getString("text");
			} else if (obj.getString("code").equals("200000")) {
				result = obj.getString("text");
				result = result + ",请访问:" + obj.getString("url");
			} else if (obj.getString("code").equals("302000")) {
				StringBuffer sb = new StringBuffer(obj.getString("text"));
				JSONArray arr =  (JSONArray) obj.get("list");
				for (int i = 0; i < arr.size() && i <=3; i++) {
					JSONObject one = (JSONObject) arr.get(i);
					sb.append("\r\n").append(one.get("article")).append(":").append(one.get("detailurl"));
				}
				return sb.toString();
			} else if (obj.getString("code").equals("308000")) {
				result = obj.getString("text");
			} else if (obj.getString("code").equals("313000")) {
				result = obj.getString("text");
			} else if (obj.getString("code").equals("314000")) {
				result = obj.getString("text");
			} else {
				result = "处理有误 " + obj.getString("code");
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return result;
	}
}
